package com.hjh.testdemo.ui.device.info

import android.os.Build
import android.view.Gravity
import android.widget.TableRow
import android.widget.TextView
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.hjh.res.R
import com.hjh.testdemo.databinding.FragmentDeviceInfoBinding
import com.hjh.testdemo.entity.DeviceInfoItem
import com.hjh.core.activity.BaseFragment
import com.hjh.tool.util.sys.UniqueIdUtil

class DeviceInfoFragment : BaseFragment<FragmentDeviceInfoBinding>() {

    private val viewModel: DeviceInfoViewModel by viewModels()

    override fun initView() {
        requestPermission(
            phoneState = true,
            onDenied = {
                findNavController().navigateUp()
            })

        val infoList = listOf(
            DeviceInfoItem(
                R.string.label_device_model,
                Build.MODEL
            ),
            DeviceInfoItem(
                R.string.label_android_version,
                "${Build.VERSION.RELEASE} (API ${Build.VERSION.SDK_INT})"
            ),
            DeviceInfoItem(
                R.string.label_android_id,
                UniqueIdUtil.getAndroidId(requireContext())
            ),
            DeviceInfoItem(
                R.string.label_imei,
                UniqueIdUtil.getIMEI(requireContext()) ?: ""
            )
        )
        viewModel.updateDeviceInfo(infoList)
    }

    override fun initObserve() {
        viewModel.deviceInfo.observe(this) {
            it?.forEach { item ->
                addTableRow(
                    getString(item.labelRes),
                    formatValue(item.value, item.isSensitive)
                )
            }
        }
    }

    private fun addTableRow(label: String, value: String) {
        TableRow(context).apply {
            addView(createLabelView(label))
            addView(createValueView(value))
            binding.tableDeviceInfo.addView(this)
        }
    }

    private fun createLabelView(text: String): TextView {
        return TextView(context).apply {
            setTextAppearance(R.style.InfoLabelStyle)
            this.text = text
            gravity = Gravity.CENTER
            isSingleLine = false
            maxLines = 5
        }
    }

    private fun createValueView(text: String): TextView {
        return TextView(context).apply {
            setTextAppearance(R.style.InfoValueStyle)
            this.text = text
            gravity = Gravity.CENTER
            isSingleLine = false
            maxLines = 5
        }
    }

    private fun formatValue(value: String, isSensitive: Boolean): String {
        return if (isSensitive && !UniqueIdUtil.hasPrivilegedAccess(requireContext())) {
            getString(R.string.requires_system_permission)
        } else {
            value.ifEmpty { getString(R.string.unknown) }
        }
    }
}
